60. Permutation Sequence - LeetCode Solution


Math Backtracking

Python Code:

class Solution:
    def getPermutation(self, n: int, k: int) -> str:
        nums = [str(x) for x in range(1, n + 1)]
        answer = ""
        while nums:
            c = len(nums)
            cfac = 1
            for num in range(1, c + 1):
                cfac *= num
            save = 1
            for index in range(1, cfac + 1, cfac//c):
                save = index
                if k > index - 1 and k < index + (cfac/c):
                    break
            get = int((save - 1)/(cfac/c))
            next = nums[get]
            answer += next
            nums.pop(get)
            k = k - (save - 1)
        return answer
        


Comments

Submit
0 Comments
More Questions

1110A - Parity
1215B - The Number of Products
604C - Alternative Thinking
1204C - Anna Svyatoslav and Maps
322A - Ciel and Dancing
1689B - Mystic Permutation
1711B - Party
1702D - Not a Cheap String
1714F - Build a Tree and That Is It
1703F - Yet Another Problem About Pairs Satisfying an Inequality
610A - Pasha and Stick
1200A - Hotelier
1091A - New Year and the Christmas Ornament
1352B - Same Parity Summands
1102A - Integer Sequence Dividing
630B - Moore's Law
1004A - Sonya and Hotels
1680B - Robots
1690A - Print a Pedestal (Codeforces logo)
1295A - Display The Number
1077A - Frog Jumping
1714G - Path Prefixes
1369C - RationalLee
289B - Polo the Penguin and Matrix
1716A - 2-3 Moves
1670B - Dorms War
1716B - Permutation Chain
987A - Infinity Gauntlet
1676G - White-Black Balanced Subtrees
1716D - Chip Move